import { AxiosRequestConfig } from "axios";
import AxiosRequest from "../axiosRequest";
import { ReturnPlugin, YFWRequestOptions } from "../types";
import {debounce, type DebounceSettings} from "lodash-es";

export function DebuouncePlugin(
  requestIns: AxiosRequest,
  options: YFWRequestOptions
): ReturnPlugin {
  const { debounceWait, debounceLeading, debounceTrailing, debounceMaxWait } =
    options;

  if (!debounceWait) {
    return {};
  }

  let debounceFn = requestIns.pluginStore.debounceFn;
  if (!debounceFn) {
    const options: DebounceSettings = {};
    if (debounceLeading) {
      options.leading = debounceLeading;
    }
    if (debounceTrailing) {
      options.trailing = debounceTrailing;
    }
    if (debounceMaxWait) {
      options.maxWait = debounceMaxWait;
    }
    const originRequest = requestIns.request.bind(requestIns);
    const debounceFn = debounce(
      (callback: any) => callback(),
      debounceWait,
      options
    );
    requestIns.request = (params: AxiosRequestConfig) => {
      return new Promise((resolve, reject) => {
        debounceFn(() => {
          originRequest(params)
            .then((res) => resolve(res as any))
            .catch(reject);
        });
      });
    };
  }
  return {}
}
